package com.lewis.module.m2;

import com.alibaba.fastjson.JSON;
import com.lewis.api.system.entity.BotFunctionMenu;
import com.lewis.common.core.entity.BaseResult;
import com.lewis.common.core.utils.DateUtil;
import com.lewis.common.core.utils.SpringUtil;
import com.lewis.common.core.utils.StringUtil;
import com.lewis.module.m2.api.bill.code.controller.BillCodeApi;
import com.lewis.module.m2.api.bill.code.entity.BillCode;
import com.lewis.module.m2.api.bill.code.vo.BillCodeDeleteVo;
import com.lewis.module.m2.api.bill.controller.BillApi;
import com.lewis.module.m2.api.bill.entity.Bill;
import com.lewis.module.m2.api.bill.vo.BillDeleteVo;
import com.lewis.module.m2.api.integral.api.ImmortalIntegralApi;
import com.lewis.module.m2.api.integral.entity.ImmortalIntegral;
import com.lewis.module.m2.api.integral.vo.ImmortalVo;
import com.lewis.module.m2.api.integral.vo.RandomGetIntegralVo;
import com.lewis.module.m2.api.luck.api.LuckApi;
import com.lewis.module.m2.api.record.controller.*;
import com.lewis.module.m2.api.record.entity.AutoReply;
import com.lewis.module.m2.api.record.entity.QqDetail;
import com.lewis.module.m2.api.record.entity.QqDetailOptions;
import com.lewis.module.m2.api.tiktok.controller.TikTokController;
import com.lewis.module.m2.utils.*;
import kotlin.coroutines.CoroutineContext;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.console.plugin.jvm.JavaPlugin;
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescriptionBuilder;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.GlobalEventChannel;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.*;
import net.mamoe.mirai.message.data.*;
import net.sf.jsqlparser.statement.select.SelectItem;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * mirai插件主体
 *
 * @author Lewis
 */
@Slf4j
public class PluginMain extends JavaPlugin {

	/**
	 * 静态初始化单例class，必须public static，并且必须命名为INSTANCE
	 */
	public static final PluginMain INSTANCE = new PluginMain();

	/**
	 * 线程池
	 */
	public static final ThreadPoolExecutor EXECUTOR_SERVICE = new ThreadPoolExecutor(
			5, 10, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10)
	);

	/**
	 * 缓冲qq
	 */
	private List<Long> qqList = new ArrayList<>();

	/**
	 * 启动时自动调用的方法
	 */
	@Override
	public void onEnable() {
		GlobalEventChannel.INSTANCE.registerListenerHost(new SimpleListenerHost() {
			@Override
			public void handleException(@NotNull CoroutineContext context, @NotNull Throwable exception) {
				super.handleException(context, exception);
			}

			/**
			 * 通用消息处理器
			 * @param event
			 */
			@EventHandler
			public void handleMessage(MessageEvent event) {
				long botQq = event.getBot().getId();
				String getMsg = event.getMessage().serializeToMiraiCode();
				log.info("【" + botQq + "】收到信息：" + getMsg);
				boolean autoReplySwitch = ConfigJsonUtils.getFunctionSwitchTrue("autoReply", botQq);
				if (autoReplySwitch) {
					msgHandleAutoReply(event);
				}
				boolean billSwitch = ConfigJsonUtils.getFunctionSwitchTrue("bill", botQq);
				if (billSwitch) {
					msgHandleBill(event);
				}
			}

			/**
			 * 好友添加请求事件处理
			 * @param event
			 */
			@EventHandler
			public void handleMessage(NewFriendRequestEvent event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("autoAccept", event.getBot().getId())) {
					// 自动同意
					event.accept();
				}
			}

			/**
			 * 邀请入群请求事件处理
			 * @param event
			 */
			@EventHandler
			public void handleMessage(BotInvitedJoinGroupRequestEvent event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("autoAccept", event.getBot().getId())) {
					// 自动同意
					event.accept();
				}
			}

			/**
			 * 入群请求事件处理
			 * @param event
			 */
			@EventHandler
			public void handleMessage(MemberJoinRequestEvent event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("autoAccept", event.getBot().getId())) {
					// 自动同意
					event.accept();
				}
			}

			/**
			 * 机器人登录事件
			 * @param event
			 */
			@EventHandler
			public void handleMessage(BotOnlineEvent event) {
				log.info("框架登录成功！");
			}

			/**
			 * 成员主动加群事件
			 * @param event
			 */
			@EventHandler
			public void handleMessage(MemberJoinEvent.Active event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("groupCommon", event.getBot().getId())) {
					if (ConfigJsonUtils.isAllowGroupId(event.getGroupId(), "groupCommon", event.getBot().getId())) {
						// 群欢迎
						MessageChainBuilder builder = new MessageChainBuilder()
								.append(Objects.requireNonNull(MiraiImageUtils.path2img(event.getGroup(), "./config/lewis-qq398529803/images/hello_yinghualangling.gif")))
								.append("\n")
								.append("欢迎新人~~\n")
								.append(new At(event.getMember().getId())).append("\n")
								.append("QQ名称：").append(event.getMember().getNick()).append("\n")
								.append("QQ号：").append(String.valueOf(event.getMember().getId())).append("\n")
								.append("加群方式：主动加群").append("\n")
								.append("您是本群的第").append(String.valueOf(event.getGroup().getMembers().size() + 1)).append("位成员哦").append(new Face(2));
						event.getGroup().sendMessage(builder.build());
						event.getMember().nudge();
					}
				}
			}

			/**
			 * 成员被邀请加群事件
			 * @param event
			 */
			@EventHandler
			public void handleMessage(MemberJoinEvent.Invite event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("groupCommon", event.getBot().getId())) {
					if (ConfigJsonUtils.isAllowGroupId(event.getGroupId(), "groupCommon", event.getBot().getId())) {
						// 群欢迎
						MessageChainBuilder builder = new MessageChainBuilder()
								.append(Objects.requireNonNull(MiraiImageUtils.path2img(event.getGroup(), "./config/lewis-qq398529803/images/hello_yinghualangling.gif")))
								.append("\n")
								.append("欢迎新人~~\n")
								.append(new At(event.getMember().getId())).append("\n")
								.append("QQ名称：").append(event.getMember().getNick()).append("\n")
								.append("QQ号：").append(String.valueOf(event.getMember().getId())).append("\n")
								.append("加群方式：被邀请加群").append("\n")
								.append("邀请人：").append(new At(event.getInvitor().getId())).append("\n")
								.append("您是本群的第").append(String.valueOf(event.getGroup().getMembers().size() + 1)).append("位成员哦").append(new Face(2));
						event.getGroup().sendMessage(builder.build());
						event.getMember().nudge();
					}
				}
			}

			/**
			 * 群员离开事件
			 * @param event
			 */
			@EventHandler
			public void handleMessage(MemberLeaveEvent.Quit event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("groupCommon", event.getBot().getId())) {
					if (ConfigJsonUtils.isAllowGroupId(event.getGroupId(), "groupCommon", event.getBot().getId())) {
						removeThisUser(event.getGroupId(), event.getUser().getId());
						MessageChainBuilder builder = new MessageChainBuilder();
						builder.append("退群者名称：").append(event.getUser().getNick()).append("\n");
						builder.append("退群者QQ：").append(String.valueOf(event.getUser().getId())).append("\n");
						builder.append("移除仙藉。");
						event.getGroup().sendMessage(builder.build());
					}
				}
			}

			/**
			 * 群员被踢事件
			 * @param event
			 */
			@EventHandler
			public void handleMessage(MemberLeaveEvent.Kick event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("groupCommon", event.getBot().getId())) {
					if (ConfigJsonUtils.isAllowGroupId(event.getGroupId(), "groupCommon", event.getBot().getId())) {
						removeThisUser(event.getGroupId(), event.getUser().getId());
						MessageChainBuilder builder = new MessageChainBuilder();
						builder.append("有人被踢出群聊......\n");
						builder.append("被踢者名称：").append(event.getUser().getNick()).append("\n");
						builder.append("被踢者QQ：").append(String.valueOf(event.getUser().getId())).append("\n");
						builder.append("踢人者：").append(new At(event.getOperator() == null ? event.getBot().getId() : event.getOperator().getId())).append("\n");
						builder.append("移除仙藉。");
						event.getGroup().sendMessage(builder.build());
					}
				}
			}

			/**
			 * 群临时消息事件处理
			 * @param event
			 */
			@EventHandler
			public void handleMessage(GroupTempMessageEvent event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("image", event.getBot().getId())) {
					// 若在合并消息中出现图片也一并保存到本地
					image2localIfForwardMessageHaveImage(event.getMessage(), event.getSender().getId());
				}
			}

			/**
			 * 陌生人消息处理
			 * @param event
			 */
			@EventHandler
			public void handleMessage(StrangerMessageEvent event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("image", event.getBot().getId())) {
					// 若在合并消息中出现图片也一并保存到本地
					image2localIfForwardMessageHaveImage(event.getMessage(), event.getSender().getId());
				}
			}

			/**
			 * 好友消息处理
			 * @param event
			 */
			@EventHandler
			public void handleMessage(FriendMessageEvent event) {
				if (ConfigJsonUtils.getFunctionSwitchTrue("image", event.getBot().getId())) {
					// 若在合并消息中出现图片也一并保存到本地
					image2localIfForwardMessageHaveImage(event.getMessage(), event.getSender().getId());
				}
				if (ConfigJsonUtils.isAdministrator(event.getSender().getId(), "functionMenu", event.getBot().getId())) {
					msgHandleFunctionMenu(event);
				}
			}

			/**
			 * 群消息处理
			 * @param event
			 */
			@EventHandler
			public void handleMessage(GroupMessageEvent event) {
				EXECUTOR_SERVICE.execute(() -> {
					if (ConfigJsonUtils.getFunctionSwitchTrue("functionMenu", event.getBot().getId())
							&& ConfigJsonUtils.isAllowGroupId(event.getGroup().getId(), "functionMenu", event.getBot().getId())
							&& ConfigJsonUtils.isAdministrator(event.getSender().getId(), "functionMenu", event.getBot().getId())) {
						msgHandleFunctionMenu(event);
					}
					if (ConfigJsonUtils.getFunctionSwitchTrue("record", event.getBot().getId())) {
						msgHandleRecord(event);
					}
					if (ConfigJsonUtils.getFunctionSwitchTrue("tiktok", event.getBot().getId())
							&& ConfigJsonUtils.isAllowGroupId(event.getGroup().getId(), "tiktok", event.getBot().getId())) {
						msgHandleTiktok(event);
					}
					if (ConfigJsonUtils.getFunctionSwitchTrue("immortal", event.getBot().getId())
							&& ConfigJsonUtils.isAllowGroupId(event.getGroup().getId(), "immortal", event.getBot().getId())) {
						msgHandleImmortal(event, event.getGroup().getId());
					}
					if (ConfigJsonUtils.getFunctionSwitchTrue("group", event.getBot().getId())
							&& ConfigJsonUtils.isAllowGroupId(event.getGroup().getId(), "group", event.getBot().getId())) {
						msgHandleGroup(event, event.getSender().getId());
					}
					if (ConfigJsonUtils.getFunctionSwitchTrue("groupCommon", event.getBot().getId())
							&& ConfigJsonUtils.isAllowGroupId(event.getGroup().getId(), "groupCommon", event.getBot().getId())
							&& ConfigJsonUtils.isAdministrator(event.getSender().getId(), "groupCommon", event.getBot().getId())) {
						msgHandleGroupCommon(event);
					}
					if (ConfigJsonUtils.getFunctionSwitchTrue("image", event.getBot().getId())) {
						// 若在合并消息中出现图片也一并保存到本地
						image2localIfForwardMessageHaveImage(event.getMessage(), event.getSender().getId());
					}
					if (ConfigJsonUtils.getFunctionSwitchTrue("select", event.getBot().getId())
							&& ConfigJsonUtils.isAllowGroupId(event.getGroup().getId(), "select", event.getBot().getId())) {
						msgHandleSelect(event);
					}
				});
			}
		});
	}

	private void msgHandleFunctionMenu(MessageEvent event) {
		// qq
		long qq = event.getSender().getId();
		// 获取消息文本
		String msg = event.getMessage().serializeToMiraiCode();
		if (msg.startsWith("指令菜单")) {
			String[] split = msg.split(" ");
			BotFunctionMenu botFunctionMenu = new BotFunctionMenu();
			if (split.length == 2) {
				botFunctionMenu.setFatherId(split[1]);
			}
			BaseResult baseResult = SpringUtil.getBean(RecordBotFunctionMenuController.class).list(botFunctionMenu);
			if (baseResult.getCode() != 200) {
				event.getSubject().sendMessage("fail");
			} else {
				List<BotFunctionMenu> maps = StringUtil.object2List(baseResult.getData(), BotFunctionMenu.class);
				MessageChainBuilder builder = new MessageChainBuilder();
				builder.append(new At(qq));
				for (BotFunctionMenu map : maps) {
					builder.append("\n")
							.append(map.getId()).append(" ").append(map.getMenuName()).append(" ").append(map.getRemark());
				}
				event.getSubject().sendMessage(builder.build());
			}
			return;
		}
		// 新增指令 指令名(空格使用kg代替) 备注 所属父id
		if (msg.startsWith("新增指令")) {
			String[] split = msg.split(" ");
			if (split.length == 4) {
				BaseResult baseResult = SpringUtil.getBean(RecordBotFunctionMenuController.class).add(new BotFunctionMenu(split[1].replaceAll("kg", " "), split[3], split[2]));
				if (baseResult.getCode() == 200) {
					event.getSubject().sendMessage("ok");
				} else {
					event.getSubject().sendMessage("fail");
				}
				return;
			}
		}
		// 删除指令 指令id
		if (msg.startsWith("删除指令")) {
			String[] split = msg.split(" ");
			if (split.length == 2) {
				BaseResult baseResult = SpringUtil.getBean(RecordBotFunctionMenuController.class).delete(split[1].split(","));
				if (baseResult.getCode() == 200) {
					event.getSubject().sendMessage("ok");
				} else {
					event.getSubject().sendMessage("fail");
				}
			}
		}
	}

	private void msgHandleGroupCommon(GroupMessageEvent event) {
		// 获取消息文本
		String msg = event.getMessage().serializeToMiraiCode();
		// 踢人
		if (msg.startsWith("踢")) {
			// 获取at对象
			MessageChain message = event.getMessage();
			At at = null;
			long setQq = 0;
			for (Message message1 : message) {
				if (message1 instanceof At) {
					at = (At) message1;
					setQq = at.getTarget();
					break;
				}
			}
			// 确保at存在
			if (at != null) {
				Group group = (Group) event.getSubject();
				Objects.requireNonNull(group.get(setQq)).kick("");
			}
		}
		// 禁言
		if (msg.startsWith("禁言")) {
			String[] split = msg.split(" ");
			if (split.length == 2) {
				// 获取at对象
				MessageChain message = event.getMessage();
				At at = null;
				long setQq = 0;
				for (Message message1 : message) {
					if (message1 instanceof At) {
						at = (At) message1;
						setQq = at.getTarget();
						break;
					}
				}
				// 确保at存在
				if (at != null) {
					Group group = (Group) event.getSubject();
					Objects.requireNonNull(group.get(setQq)).mute(Integer.parseInt(split[1]));
				}
			}
		}
		// 解禁
		if (msg.startsWith("解禁")) {
			// 获取at对象
			MessageChain message = event.getMessage();
			At at = null;
			long setQq = 0;
			for (Message message1 : message) {
				if (message1 instanceof At) {
					at = (At) message1;
					setQq = at.getTarget();
					break;
				}
			}
			// 确保at存在
			if (at != null) {
				Group group = (Group) event.getSubject();
				Objects.requireNonNull(group.get(setQq)).unmute();
			}
		}
	}

	private void msgHandleSelect(GroupMessageEvent event) {
		// 获取消息文本
		String msg = event.getMessage().serializeToMiraiCode();
		// qq
		long qq = event.getSender().getId();

		if ("米兔帮帮我".equals(msg)) {
			qqList.add(qq);
			event.getSubject().sendMessage("请发送所有选项，发送后将会从中帮你选择一个。");
		} else {
			// 判断是否存在该qq
			if (qqList.contains(qq)) {
				String[] split = msg.split(" ");
				Random random = new Random();
				event.getSubject().sendMessage(split[random.nextInt(split.length)]);
				// 移除该qq
				qqList.remove(qq);
			}
		}

	}

	private void msgHandleRecord(GroupMessageEvent event) {
		// qq
		long qq = event.getSender().getId();
		// 获取消息文本
		String msg = event.getMessage().serializeToMiraiCode();

		// 存记录
		QqDetail qqDetail = new QqDetail();
		qqDetail.setCTime(DateUtil.current());
		qqDetail.setQq(qq);
		qqDetail.setBotQq(event.getBot().getId());
		qqDetail.setContent(msg);
		qqDetail.setDetailType(2);
		qqDetail.setContentType(MiraiMessageUtils.getMsgType(event.getMessage()));
		qqDetail.setIsSend(0);
		QqDetailOptions qqDetailOptions = new QqDetailOptions();
		qqDetailOptions.setGroupId(event.getGroup().getId());
		qqDetail.setOptions(qqDetailOptions);
		SpringUtil.getBean(RecordQqDetailController.class).add(qqDetail);
	}

	private void msgHandleTiktok(GroupMessageEvent event) {
		long qq = event.getSender().getId();
		// 获取消息文本
		String msg = event.getMessage().serializeToMiraiCode();
		if (msg.startsWith("解析抖音图集")) {
			// 扣除88积分
			BaseResult baseResult = IntegralUtils.cutIntegral(event, event.getSender().getId(), 88);
			if (baseResult.getCode() != 200 || baseResult.getData() == null) {
				event.getSubject().sendMessage(new MessageChainBuilder()
						.append(new QuoteReply(event.getMessage()))
						.append(baseResult.getMsg()).build()
				);
				return;
			}
			analysis(event, msg);
		}
		if (msg.startsWith("解析抖音视频")) {
			// 扣除88积分
			BaseResult baseResult = IntegralUtils.cutIntegral(event, event.getSender().getId(), 88);
			if (baseResult.getCode() != 200 || baseResult.getData() == null) {
				event.getSubject().sendMessage(new MessageChainBuilder()
						.append(new QuoteReply(event.getMessage()))
						.append(baseResult.getMsg()).build()
				);
				return;
			}
			// 解析视频
			// event.getGroup().getFiles().uploadNewFile()
		}
	}

	/**
	 * 解析图片处理
	 */
	private void analysis(MessageEvent event, String msg) {
		String[] split = msg.split(" ");
		if (split.length == 2) {
			BaseResult baseResult = SpringUtil.getBean(TikTokController.class).getNoWatermarkImageUrlList(split[1].replace("\\", ""));
			if (baseResult.getCode() == 200) {
				// 列表处理
				List<String> imageList = StringUtil.object2List(baseResult.getData(), String.class);
				// 拼接合并发送卡片
				ForwardMessageBuilder builder = new ForwardMessageBuilder(event.getSubject());
				imageList.forEach(image -> builder.add(event.getBot().getId(), event.getBot().getNick(), Objects.requireNonNull(MiraiImageUtils.path2img(event.getSubject(), image))));
				event.getSubject().sendMessage(builder.build());
			}
		}
	}

	private void image2localIfForwardMessageHaveImage(MessageChain messageChain, long qq) {
		// 合并消息实例
		String demo = "[mirai:source:[20467],[-1981843161]]" +
				"[mirai:origin:FORWARD,bIa66H+Eh9XqPil8eEju+jqIVkDCd7QoA2vGc18IYjtScW57ByKcs693OC6APczN]" +
				"ForwardMessage(" +
				"preview=[米兔少女:我不, 米兔少女:我在w], " +
				"title=米兔少女和空的聊天记录, " +
				"brief=[聊天记录], " +
				"source=聊天记录, " +
				"summary=查看转发消息, " +
				"nodeList=[" +
				"Node(senderId=3364684344, time=1638437158, senderName=米兔少女, messageChain=我不), " +
				"Node(senderId=3364684344, time=1638437158, senderName=米兔少女, messageChain=我在w)" +
				"])";
		List<ForwardMessage> list = new ArrayList<>();
		for (SingleMessage message : messageChain) {
			if (message instanceof ForwardMessage) {
				list.add((ForwardMessage) message);
			}
		}
		if (list.size() != 0) {
			for (ForwardMessage forwardMessage : list) {
				for (ForwardMessage.Node node : forwardMessage.getNodeList()) {
					MessageChain messageChain1 = node.getMessageChain();
					for (SingleMessage singleMessage : messageChain1) {
						// 若存在image，保存到本地
						image2localIfHaveImage(qq, singleMessage);
						// 若存在多层合并消息，递归
						if (singleMessage instanceof ForwardMessage) {
							image2localIfForwardMessageHaveImage(messageChain1, qq);
						}
					}
				}
			}
		}
	}

	private void image2localIfHaveImage(long qq, Message message) {
		if (message instanceof Image) {
			Image image = (Image) message;
			String queryUrl = Image.queryUrl(image);
			ImageType imageType = image.getImageType();
			// 图片保存到本地
			String filePath = "./data/lewis-qq398529803/images/" + DateUtil.getYear() + "/" + DateUtil.getMonth() + "/" + DateUtil.getDay();
			// 处理文件名
			String fileName = getFileName(imageType);
		}
	}

	@NotNull
	private String getFileName(ImageType imageType) {
		String fileName = "";
		if (imageType.toString().equals("UNKNOWN")) {
			fileName = "image_" + DateUtil.dateTimeNow() + new Random().nextInt(9) + "." + "jpg";
		} else {
			fileName = "image_" + DateUtil.dateTimeNow() + new Random().nextInt(9) + "." + imageType;
		}
		return fileName;
	}

	private void msgHandleAutoReply(MessageEvent event) {
		// 获取消息文本
		String msg = event.getMessage().serializeToMiraiCode().replace("\\", "");

		if (msg.equals("")) {
			return;
		}

		// 跟我学
		if (msg.startsWith("跟我学")) {
			if (ConfigJsonUtils.isAdministrator(event.getSender().getId(), "autoReply", event.getBot().getId())) {
				String[] split = msg.split(" ");
				if (split.length == 3) {
					String command = split[1];
					String content = split[2];
					AutoReply param = new AutoReply();
					param.setCommand(command);
					param.setMsg(content);
					param.setCTime(DateUtil.current());
					BaseResult addResult = SpringUtil.getBean(RecordAutoReplyController.class).add(param);
					event.getSubject().sendMessage("ok");
				}
			}
			return;
		}

		// 自动回复
		if (MiraiMessageUtils.getMsgType(event.getMessage()) == 1) {
			AutoReply autoReply = new AutoReply();
			autoReply.setCommand(msg.replace("\\", ""));
			BaseResult baseResult = SpringUtil.getBean(RecordAutoReplyController.class).getOne(autoReply);
			if (baseResult.getCode() == 200) {
				AutoReply resultAutoReply = StringUtil.object2JavaBean(baseResult.getData(), AutoReply.class);
				String replyMsg = resultAutoReply.getMsg();
				event.getSubject().sendMessage(new MessageChainBuilder().append(new QuoteReply(event.getMessage())).append(replyMsg).build());
			}
		}
	}

	/**
	 * 移除指定群指定用户积分信息
	 *
	 * @param groupId
	 * @param qq
	 */
	private void removeThisUser(long groupId, long qq) {
		// 删除指定群指定用户信息
		ImmortalVo vo = new ImmortalVo();
		vo.setGroupId(String.valueOf(groupId));
		vo.setQq(String.valueOf(qq));
		SpringUtil.getBean(ImmortalIntegralApi.class).delete(vo);
	}

	/**
	 * 消息处理
	 *
	 * @param event 消息实体
	 */
	private void msgHandleGroup(MessageEvent event, long qq) {
		// 获取消息文本
		String msg = event.getMessage().serializeToMiraiCode();
		// 改头衔
		extracted(event, msg, qq);
		// 上下管理
		extracted1(event, msg, qq);
	}

	private void extracted1(MessageEvent event, String msg, long qq) {
		extracted2(event, msg, "上管理", true, qq);
		extracted2(event, msg, "下管理", false, qq);
	}

	private void extracted2(MessageEvent event, String msg, String command, boolean isOrNo, long qq) {
		if (msg.startsWith(command)) {
			// 确保有管理员权限
			if (ConfigJsonUtils.isAdministrator(qq, "group", event.getBot().getId())) {
				// 获取at对象
				MessageChain message = event.getMessage();
				At at = null;
				long setQq = 0;
				for (Message message1 : message) {
					if (message1 instanceof At) {
						at = (At) message1;
						setQq = at.getTarget();
						break;
					}
				}
				// 确保at存在
				if (at != null) {
					Group group = (Group) event.getSubject();
					Objects.requireNonNull(group.get(setQq)).modifyAdmin(isOrNo);
				}
			}
		}
	}

	private void extracted(MessageEvent event, String msg, long qq) {
		if (msg.startsWith("改头衔")) {
			// 确保有管理员权限
			if (ConfigJsonUtils.isAdministrator(qq, "group", event.getBot().getId())) {
				// 获取at对象
				MessageChain message = event.getMessage();
				At at = null;
				long setQq = 0;
				for (Message message1 : message) {
					if (message1 instanceof At) {
						at = (At) message1;
						setQq = at.getTarget();
						break;
					}
				}
				// 确保at存在
				if (at != null) {
					String[] split = msg.split(" ");
					if (split.length == 2) {
						String headName = split[1];
						Group group = (Group) event.getSubject();
						Objects.requireNonNull(group.get(setQq)).setSpecialTitle(headName);
					}
				}
			}
		}
	}

	private PluginMain() {
		super(new JvmPluginDescriptionBuilder("com.lewis.mirai.plugin", "8.8")
				.name("mirai插件")
				.info("mirai插件")
				.author("Lewis-qq398529803")
				.build());
	}

	/**
	 * 消息处理
	 *
	 * @param event 消息实体
	 */
	private void msgHandleBill(MessageEvent event) {

		// 获取消息文本
		String msg = event.getMessage().serializeToMiraiCode();

		long qq = event.getSender().getId();

		if (msg.startsWith("支出")) {
			extracted(event, msg, qq, 0);
		}

		if (msg.startsWith("收入")) {
			extracted(event, msg, qq, 1);
		}

		if (msg.startsWith("删除明细")) {
			String[] split = msg.split(" ");
			if (split.length == 3) {
				String id = split[1];
				BillDeleteVo vo = new BillDeleteVo();
				vo.setId(Long.parseLong(id));
				vo.setQq(String.valueOf(event.getSender().getId()));
				vo.setBillCodeId(split[2]);
				BaseResult deleteResult = SpringUtil.getBean(BillApi.class).delete(vo);
				String resultJsonStr = JSON.toJSON(deleteResult).toString();
				MessageChainBuilder builder = new MessageChainBuilder().append(new QuoteReply(event.getMessage()));
				MiraiMessageUtils.getResultMsg(resultJsonStr, builder);
				event.getSubject().sendMessage(builder.build());
			}
		}

		if (msg.equals("我的账单")) {
			BillCode billCode = new BillCode();
			billCode.setQq(String.valueOf(event.getSender().getId()));
			BaseResult listResult = SpringUtil.getBean(BillCodeApi.class).list(billCode);
			String resultJsonStr = JSON.toJSON(listResult).toString();
			ForwardMessageBuilder builder = new ForwardMessageBuilder(event.getSubject());
			MiraiMessageUtils.getResultMsgForward(event, resultJsonStr, builder);
			event.getSubject().sendMessage(builder.build());
		}

		if (msg.startsWith("创建账单")) {
			String[] split = msg.split(" ");
			if (split.length == 2) {
				BillCode billCode = new BillCode();
				billCode.setQq(String.valueOf(event.getSender().getId()));
				billCode.setBillName(split[1]);
				BaseResult addResult = SpringUtil.getBean(BillCodeApi.class).add(billCode);
				String resultJsonStr = JSON.toJSON(addResult).toString();
				MessageChainBuilder builder = new MessageChainBuilder().append(new At(qq)).append("\n");
				MiraiMessageUtils.getResultMsg(resultJsonStr, builder);
				event.getSubject().sendMessage(builder.build());
			}
		}

		if (msg.startsWith("删除账单")) {
			String[] split = msg.split(" ");
			if (split.length == 2) {
				BillCodeDeleteVo vo = new BillCodeDeleteVo();
				vo.setQq(String.valueOf(event.getSender().getId()));
				vo.setBillCodeId(Integer.parseInt(split[1]));
				BaseResult deleteResult = SpringUtil.getBean(BillCodeApi.class).delete(vo);
				String resultJsonStr = JSON.toJSON(deleteResult).toString();
				MessageChainBuilder builder = new MessageChainBuilder().append(new At(qq)).append("\n");
				MiraiMessageUtils.getResultMsg(resultJsonStr, builder);
				event.getSubject().sendMessage(builder.build());
			}
		}

		if (msg.startsWith("查询明细")) {
			BaseResult listResult = SpringUtil.getBean(BillApi.class).list(setParam(msg, event.getSender().getId()));
			String resultJsonStr = JSON.toJSON(listResult).toString();
			ForwardMessageBuilder builder = new ForwardMessageBuilder(event.getSubject());
			MiraiMessageUtils.getResultMsgForward(event, resultJsonStr, builder);
			event.getSubject().sendMessage(builder.build());
		}

		if (msg.startsWith("查询余额")) {
			BaseResult balanceResult = SpringUtil.getBean(BillApi.class).balance(setParam(msg, qq));
			String resultJsonStr = JSON.toJSON(balanceResult).toString();
			MessageChainBuilder builder = new MessageChainBuilder().append(new At(qq)).append("\n");
			MiraiMessageUtils.getResultMsg(resultJsonStr, builder);
			event.getSubject().sendMessage(builder.build());
		}
	}

	private Bill setParam(String msg, long qq) {
		Bill bill = new Bill();
		String[] split = msg.split(" ");
		// 未附带日期
		if (split.length == 2) {
			bill.setQq(String.valueOf(qq));
			bill.setBillCodeId(Integer.parseInt(split[1]));
		}
		// 附带日期
		if (split.length == 3) {
			bill.setQq(String.valueOf(qq));
			bill.setBillCodeId(Integer.parseInt(split[1]));
			bill.setCtime(DateUtil.parseDate(split[2]));
		}
		return bill;
	}

	private void extracted(MessageEvent event, String msg, long qq, Integer billType) {
		String[] split = msg.split(" ");
		if (split.length == 4) {
			String billCode = split[3];
			String moneyTest = split[1];
			try {
				double money = Double.parseDouble(moneyTest);
				String remark = split[2];
				Bill bill = new Bill();
				bill.setQq(String.valueOf(event.getSender().getId()));
				bill.setBillType(billType);
				bill.setMoney(money);
				bill.setRemark(remark);
				bill.setBillCodeId(Integer.parseInt(billCode));
				BaseResult addResult = SpringUtil.getBean(BillApi.class).add(bill);
				MessageChainBuilder builder = new MessageChainBuilder().append(new QuoteReply(event.getMessage()));
				String resultJsonStr = JSON.toJSON(addResult).toString();
				MiraiMessageUtils.getResultMsg(resultJsonStr, builder);

				event.getSubject().sendMessage(builder.build());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void msgHandleImmortal(MessageEvent event, long groupId) {
		// 获取消息文本
		String msg = event.getMessage().serializeToMiraiCode();
		// qq
		long qq = event.getSender().getId();

		MessageChainBuilder builder = new MessageChainBuilder();
		builder.append(new QuoteReply(event.getMessage()));
		int flag = 0;

		switch (msg) {
			case "修仙":
				immortal(event, groupId, qq, builder);
				flag++;
				break;
			case "抽签":
				getLuck(event, qq, builder);
				flag++;
				break;
			case "堕仙":
				extracted(event, groupId, qq);
				break;
			default:
				// 指定概率获得仙力
				randomGetIntegral(event, groupId, qq, builder);
				break;
		}

		if (flag != 0) {
			event.getSubject().sendMessage(builder.build());
		}
	}

	private void extracted(MessageEvent event, long groupId, long qq) {
		// 删除指定群指定用户信息
		ImmortalVo vo = new ImmortalVo();
		vo.setGroupId(String.valueOf(groupId));
		vo.setQq(String.valueOf(qq));
		SpringUtil.getBean(ImmortalIntegralApi.class).delete(vo);
		event.getSubject().sendMessage(new MessageChainBuilder()
				.append(new At(qq)).append("\n")
				.append("堕仙结束，有缘再见！").build());
	}

	private void immortal(MessageEvent event, long groupId, long qq, MessageChainBuilder builder) {
		builder.append(Objects.requireNonNull(MiraiImageUtils.path2img(event.getSubject(), "./config/lewis-qq398529803/images/immortal.jpg")));
		builder.append("\n");
		ImmortalVo vo = new ImmortalVo();
		vo.setQq(String.valueOf(qq));
		vo.setGroupId(String.valueOf(groupId));
		BaseResult baseResult = SpringUtil.getBean(ImmortalIntegralApi.class).immortal(vo);
		MiraiMessageUtils.getResultMsg(JSON.toJSONString(baseResult), builder);
	}

	private void getLuck(MessageEvent event, long qq, MessageChainBuilder builder) {
		builder.append(Objects.requireNonNull(MiraiImageUtils.path2img(event.getSubject(), "./config/lewis-qq398529803/images/luck.png"))).append("\n");
		long groupId = event.getSubject().getId();
		BaseResult baseResult = SpringUtil.getBean(LuckApi.class).getLuck(String.valueOf(qq), String.valueOf(groupId));
		MiraiMessageUtils.getResultMsg(JSON.toJSONString(baseResult), builder);
	}

	private void randomGetIntegral(MessageEvent event, long groupId, long qq, MessageChainBuilder builder) {
		if (MathUtils.getProbability(ConfigJsonUtils.getConfigJson("immortal", event.getBot().getId()).getDouble("probabilityToGetImmortal")) == 1) {
			ImmortalIntegral immortalIntegral = SpringUtil.getBean(ImmortalIntegralApi.class).getByQq(String.valueOf(qq), String.valueOf(groupId));
			if (immortalIntegral != null) {
				int addIntegral = new Random().nextInt(9);
				RandomGetIntegralVo vo = new RandomGetIntegralVo();
				vo.setQq(String.valueOf(qq));
				vo.setGroupId(String.valueOf(groupId));
				vo.setAddIntegral(addIntegral);
				if (SpringUtil.getBean(ImmortalIntegralApi.class).randomGetIntegral(vo)) {
					builder.append("遇见了神明，收到神明的恩赐【").append(String.valueOf(addIntegral)).append("】仙力！");
					event.getSubject().sendMessage(builder.build());
				}
			}
		}
	}
}